import axios from "axios";
import Element from 'element-ui'
import router from "./router";

axios.defaults.baseURL = "http://localhost/api"

const request = axios.create({
    timeout: 5000,
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
    }
})
// 请求拦截器
request.interceptors.request.use(config => {
    config.headers['Authorization'] = localStorage.getItem("token") // 请求头带上token
    return config
})
// 响应拦截器
request.interceptors.response.use(
    response => {
        let res = response.data;
        if (response.status === 200) {
            return response
        } else {
            Element.Message.error(res.data.msg? res.data.msg : '系统异常！', {duration: 3 * 1000})
            return Promise.reject(response.data.msg)
        }
    },
    error => {
        let err = error.response;
        if (!err) {
            return;
        }
        if(err.status === 401 && router.currentRoute.path !== "/login") {
            router.push("/login")
        }
        if (err && err.data && err.data.msg) {
            Element.Message.error(err.data.msg, {duration: 3 * 1000})
        }
        return Promise.reject(err)
    }
)
export default request